
package com.winning.sx.microframework.controller.base;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.winning.dapi.data.entity.DataTable;
import com.winning.sx.microframework.common.util.BaseUtil;
import com.winning.sx.microframework.common.util.Constains;
import com.winning.sx.microframework.common.util.EncryptionUtil;
import com.winning.sx.microframework.common.util.Tools;
import com.winning.sx.microframework.model.exception.CustomException;
import com.winning.sx.microframework.model.manage.LoginSession;
import com.winning.sx.microframework.model.message.AjaxDataResponseMessage;
import com.winning.sx.microframework.model.message.AjaxTableResponseMessage;
import com.winning.sx.microframework.service.EasyService;
import com.winning.sx.microframework.service.base.EquipmentService;
import com.winning.sx.microframework.service.sysmanage.ConstService;
import com.winning.sx.microframework.service.sysmanage.UserNewService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/cust/staff")
public class CustStaffController {
    @Autowired
    EasyService easyService;
    @Autowired
    UserNewService service;
    @Autowired
    ConstService constService;
    @Autowired
    EquipmentService equipmentService;

    @RequestMapping(value = {"/", ""})
    public ModelAndView init() throws IOException, CustomException {
        ModelAndView mv = new ModelAndView("/base/customer");
        return mv;
    }

    // 客户机构管理查询
    @ResponseBody
    @RequestMapping(value = {"/queryList"})
    public AjaxTableResponseMessage queryMessageList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            String staffInformation = param.get("staffInformation");
            String oid = param.get("organizationId");
            Map paramSql = new HashMap();
            paramSql.put("wxSearch", param.get("wxSearch"));
            paramSql.put("role", param.get("role"));
            if (oid != null && oid.length() >= 1) {
                paramSql.put("organizationId", oid);
            } else {
                LoginSession login = (LoginSession) (SecurityUtils.getSubject().getSession().getAttribute("loginSession"));
                paramSql.put("organizationId", login.getSuperOrgId().toString());
            }
            //获取本机构和下级机构
            Map orgParam = new HashMap();
            orgParam.put("superOrganizationId", paramSql.get("organizationId").toString());
            orgParam.put("organizationType", "400001");
            Map org = constService.queryMyOrg(orgParam);

            String sql = "select s.*,r.cRoleName,org.name orgName ,w.name wxName,w.createTime validTime,w.state wxState,w.id wxId from BASE_Staff s" +
                    " left join BASE_Organization org on s.organizationId= org.id " +
                    " left join PM_ROLES r on r.cRoleID=s.role" +
                    "  left join PM_StaffWeChat w on s.id=w.staffId and w.validFlag='100001' " +
                    "  where s.validFlag='100001' and s.organizationId in ( " +
                    " select id from BASE_Organization o where 1=1 and o.validFlag='100001'" +
                    (paramSql.get("organizationId") != null ? " and o.id in (" + org.get("allorgs").toString() + ")" : "") +
                    " and organizationType='400001') " +
                    ("1".equals(paramSql.get("wxSearch")) ? " and w.id is not null " : "") +
                    ("2".equals(paramSql.get("wxSearch")) ? " and w.id is null " : "") +
                    (paramSql.get("role") != null ? (" and r.cRoleID= '" + paramSql.get("role")) + "'" : "") +
                    (paramSql.get("staffInformation") != null ? (" and s.telephone like " + "'" + paramSql.get("staffInformation")) + "%'" : "") +
                    (paramSql.get("staffInformation") != null ? (" and s.name like " + "'" + paramSql.get("staffInformation")) + "%'" : "") +
                    " order by s.createTime desc";
            DataTable all = easyService.querySql(sql, paramSql);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/save"})
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxDataResponseMessage insert(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                Map mapNew = new HashMap();
                String staffId = null;
                String cUserID = null;
                map = objectMapper.readValue(datas, Map.class);
                //添加拼音码
                map.put("pym", Tools.getFirstSpell(map.get("name").toString()));
                //根据手机号判断是否存在该员工
                Map staffParam = new HashMap();
                staffParam.put("telephone", map.get("telephone"));
                if (map.get("telephone") == null || "".equals(map.get("telephone"))) {
                    throw new Exception("认证号不能为空");
                }
                Map staffEntity = easyService.queryEntity("BASE_Staff", staffParam);
                Map oldStaffEntity = null;
                if (staffEntity == null) {
                    //手机号不重复
                    if ("".equals(map.get("id").toString()) || !map.containsKey("id")) {
                        //新增用户
                        map.put("validState", Constains.SYS_VALIDFLAG_TRUE);
//                        map.put("validCode",createValCode(6));
                        map.put("validCode", "123456");//新增用户同意默认验证码
                        map.put("state", "200001");
                        map.remove("wxState");
                        map.remove("wxId");
                        easyService.save("BASE_Staff", "id", map);
                        staffId = map.get("id").toString();
                        //首先是必须创建用户的，是否有角色不管，否则后续修改再删除用户，再创建用户会很麻烦
                        //将信息插入用户表
                        Map userParam = new HashMap();
                        userParam.put("cUserID", BaseUtil.createUUID());
                        userParam.put("cPassword", EncryptionUtil.getHash(map.get("validCode").toString()));
                        userParam.put("cUserCode", map.get("telephone"));
                        userParam.put("cUserName", map.get("name").toString());
                        userParam.put("bState", "True");
                        service.insert("PM_USERS", userParam);
                        cUserID = userParam.get("cUserID").toString();
                    } else {
                        //修改用户
                        staffId = map.get("id").toString();
                        Map old = new HashMap();
                        old.put("id", staffId);
                        oldStaffEntity = easyService.queryEntity("BASE_Staff", old);
                        Map userUpdate = new HashMap();
                        userUpdate.put("cUserCode", map.get("telephone"));
                        userUpdate.put("cUserName", map.get("name").toString());
                        userUpdate.put("bState", "True");
                        Map userParam = new HashMap();
                        userParam.put("cUserCode", oldStaffEntity.get("telephone"));
                        easyService.update("PM_USERS", userParam, userUpdate);
                        Map staffUpdateParam = new HashMap();
                        staffUpdateParam.putAll(map);
                        staffUpdateParam.remove("wxState");
                        staffUpdateParam.remove("wxId");
                        easyService.update("BASE_Staff", "id", staffUpdateParam);
                    }
                } else {
                    if ("".equals(map.get("id").toString()) || !map.containsKey("id")) {
                        //不允许新增
                        throw new CustomException(1, "已经存在此手机号码的员工，无法重复录入！");
                    } else {
                        //如果是修改，那么新手机号和原手机号是同一个的情况才允许修改
                        staffId = map.get("id").toString();
                        if (staffEntity.get("id").toString().equals(staffId)) {
                            Map staffUpdateParam = new HashMap();
                            staffUpdateParam.putAll(map);
                            staffUpdateParam.remove("wxState");
                            staffUpdateParam.remove("wxId");
                            easyService.update("BASE_Staff", "id", staffUpdateParam);
                            Map old = new HashMap();
                            old.put("id", staffId);
                            oldStaffEntity = easyService.queryEntity("BASE_Staff", old);
                            Map userUpdate = new HashMap();
                            userUpdate.put("cUserCode", map.get("telephone"));
                            userUpdate.put("cUserName", map.get("name").toString());
                            userUpdate.put("bState", "True");
                            Map userParam = new HashMap();
                            userParam.put("cUserCode", oldStaffEntity.get("telephone"));
                            easyService.update("PM_USERS", userParam, userUpdate);
                        } else {
                            throw new CustomException(1, "已经存在此手机号码的员工，无法重复录入！");
                        }
                    }
                }
                //先把他的角色查出来，删掉所有角色记录，然后重新插入角色记录
                Map deleteParam = new HashMap();
                deleteParam.put("cUserCode", map.get("telephone"));
                easyService.deleteDeep("delete from PM_UserAsRole where cUserID in (select cUserID from PM_USERS where cUserCode=:cUserCode)", deleteParam);
                easyService.deleteDeep("delete from PM_StaffAsUser where staffId ="+staffId,new HashMap<>());
                Map user = easyService.queryEntity("PM_USERS", deleteParam);
                if (user == null) {
                    //如果从来没有创建过那么在创建一次。目前就只有超管出现过这个问题
                }
                if (!"".equals(map.get("role")) && map.containsKey("role") == true) {
                    //有角色
                    Map relaRoleUser = new HashMap();
                    relaRoleUser.put("cUserID", user.get("cUserID").toString());
                    relaRoleUser.put("cRoleID", map.get("role").toString());
                    service.insertRela("PM_UserAsRole", relaRoleUser);

                    //将信息插入员工用户关联表
                    Map relaUserStaff = new HashMap();
                    relaUserStaff.put("userId", user.get("cUserID").toString());
                    relaUserStaff.put("staffId", staffId);
                    service.insertRela("PM_StaffAsUser", relaUserStaff);
                }
                if (map.get("wxState") != null && (!"".equals(map.get("wxState")))) {
                    Map wxParam = new HashMap();
                    wxParam.put("id", map.get("wxId").toString());
                    wxParam.put("state", map.get("wxState").toString());
                    easyService.update("PM_StaffWeChat", "id", wxParam);
                }
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/password"})
    public AjaxDataResponseMessage password(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                Map param = new HashMap();
                String id = map.get("id");
                param.put("id", id);
                Map staffEntity = easyService.queryEntity("BASE_Staff", param);
                if (staffEntity != null) {
                    Map staffParam = new HashMap();
                    String roleName = staffEntity.get("role").toString();
                    staffParam.put("cRoleName", roleName);
                    Map roleEntity = easyService.queryEntity("PM_ROLES", staffParam);
                    if (roleEntity != null) {
                        Map roleParam = new HashMap();
                        String roleId = roleEntity.get("cRoleID").toString();
                        roleParam.put("cRoleID", roleId);
                        Map relaEntity = easyService.queryEntity("PM_UserAsRole", roleParam);
                        if (relaEntity != null) {
                            Map relaParam = new HashMap();
                            String userId = relaEntity.get("cUserID").toString();
                            relaParam.put("cUserID", userId);
                            Map userEntity = easyService.queryEntity("PM_USERS", relaParam);
                            if (userEntity != null) {
                                Map userParam = new HashMap();
                                String userid = userEntity.get("cUserID").toString();
                                userParam.put("cUserID", userid);
                                Map userP = new HashMap();
                                userP.put("cPassword", "E10ADC3949BA59ABBE56E057F20F883E");
                                easyService.update("PM_USERS", userParam, userP);
                                ajaxDataResponseMessage.setSuccess(true);
                            }
                        }
                    } else {
                        ajaxDataResponseMessage.setSuccess(true);
                        ajaxDataResponseMessage.setErrorMsg("此角色不存在，初始化密码失败");
                    }
                }

            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/delete"})
    public AjaxDataResponseMessage delete(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                easyService.delete("BASE_Staff", "id", map);
                easyService.deleteDeep("delete from PM_UserAsRole where cUserID in (select cUserID from PM_USERS where  cUserCode=:code)",map);
                easyService.deleteDeep("delete from PM_USERS where cUserCode=:code",map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    //验证码
    @ResponseBody
    @RequestMapping(value = {"/editYZM"})
    public AjaxDataResponseMessage editYZM(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                map.put("validState", Constains.SYS_VALIDFLAG_TRUE);
                map.put("validCode", createValCode(6));
                easyService.save("BASE_Staff", "id", map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    public static String createValCode(int length) {
        String validateCode = "";
        for (int i = 0; i < length; i++) {
            validateCode += String.valueOf(Math.round(Math.random() * 8 + 1));
        }
        return validateCode;
    }
}

